package de.ubschmidt.capi;

import de.ubschmidt.capi.util.StringUtil;
import java.nio.ByteBuffer;

/**
 *
 */
public abstract class TypedNumber
        implements ByteBufferWritable {

    /** The type of the number. */
    private byte _type = (byte) 0x00;

    /** The number. */
    private String _number = null;

    /**
     * Creates a new, empty number of type 0x00.
     */
    public TypedNumber() {
    }

    /**
     *
     * @param byteBuffer
     */
    public TypedNumber(final ByteBuffer byteBuffer) {
        byte [] buf = CapiStruct.readStructContent(byteBuffer);

        if (buf.length >= 1) {
            setType(buf[0]);
            setNumber(StringUtil.string(buf, 1));
        }
    }

    /**
     *
     * @return
     */
    public byte getType() {
        return _type;
    }

    /**
     *
     * @param type
     */
    public void setType(final byte type) {
        _type = type;
    }

    /**
     * Retrieve the number.
     *
     * @return The number.
     */
    public String getNumber() {
        return _number;
    }

    /**
     * Set the number.
     *
     * @param number The number.
     */
    public void setNumber(final String number) {
        _number = number;
    }

    /** {@inheritDoc} */
    public void writeTo(final ByteBuffer byteBuffer) {
        String number = getNumber();

        if (number == null) {
            // empty struct
            byteBuffer.put((byte) 0);
        } else {
            int length = 1 + number.length();

            CapiStruct.writeStructLength(byteBuffer, length);
            byteBuffer.put(getType());
            byteBuffer.put(StringUtil.byteBuf(number));
        }
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        String number = getNumber();
        String clazzName = getClass().getSimpleName();

        if (number == null) {
            return String.format("%s[empty]", clazzName);
        } else {
            return String.format("%s[type=0x%02x #='%s']",
                    clazzName,
                    getType(),
                    number);
        }
    }

}
